﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using QuanLyHopDong.Biz.Model;

namespace QuanLyHopDong.Biz
{
    public class DiaDiemBiz
    {
        #region Selection

        public List<DiaDiem> SearchDiaDiem(string ma)
        {
            using (var db = new HopDongEntities())
            {
                return db.DiaDiems.Where(x => x.Ma.Contains(ma)).ToList();
            }
        }

        public List<DiaDiem> GetDiaDiems(int startIndex, int pageSize, string sorting, string ma, out int totalRecords)
        {
            using (var db = new HopDongEntities())
            {
                var query = from item in db.DiaDiems
                            select item;

                // filter
                if (!string.IsNullOrEmpty(ma))
                {
                    query = query.Where(x => x.Ma.Contains(ma));
                }

                totalRecords = query.Count();

                return pageSize > 0
                           ? query.OrderBy(sorting).Skip(startIndex).Take(pageSize).ToList() //Paging
                           : query.ToList(); //No paging
            }
        }

        #endregion

        #region CRUD

        public void CreateDiaDiem(DiaDiem diaDiem)
        {
            using (var db = new HopDongEntities())
            {
                // NameIsExisted
                var count = (from o in db.DiaDiems
                             where (o.Ma == diaDiem.Ma)
                             select o.Id).Count();

                if (count > 0)
                    throw new ApplicationException("NameIsExisted");

                db.DiaDiems.Add(diaDiem);
                db.SaveChanges();
            }
        }

        public void UpdateDiaDiem(DiaDiem diaDiem)
        {
            using (var db = new HopDongEntities())
            {
                //NameIsExisted
                var count = (from o in db.DiaDiems
                             where (o.Ma == diaDiem.Ma) && (o.Id != diaDiem.Id)
                             select o.Id).Count();

                if (count > 0)
                    throw new ApplicationException("NameIsExisted");

                db.DiaDiems.Attach(diaDiem);
                db.Entry(diaDiem).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        #endregion
    }
}
